const log = require('electron-log');
const path = require('path');
const fs = require('fs');
const dayjs = require('dayjs');
const { BrowserWindow } = require('electron');

// 设置日志文件级别和大小
log.transports.file.level = 'info';
log.transports.file.maxSize = 5 * 1024 * 1024; // 5MB

// 构建日志路径
const logPath = path.join(path.resolve(__dirname, '../..').replace('app.asar', ''), 'logs');
if (!fs.existsSync(logPath)) {
    fs.mkdirSync(logPath);
}

// 设置日志文件的路径
const logFilePath = path.join(logPath, `${dayjs().format('YYYY-MM-DD')}.log`);
log.transports.file.resolvePath = () => logFilePath;

// 获取当前时间戳
const getTimestamp = () => dayjs().format('YYYY-MM-DD HH:mm:ss');

// 提取通用的日志发送逻辑
const sendLogToWindows = (type, message) => {
    const windows = BrowserWindow.getAllWindows();
    windows.forEach((win) => {
        if (win.winId === 'homeWin') {
            win.webContents.send('logs', { type, message });
        }
    });
};

// 包装 log.info
const originalInfo = log.info;
log.info = (...args) => {
    const timestamp = `[${getTimestamp()}]`;
    const formattedMessage = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : arg)).join(' ');
    originalInfo(`${timestamp} [INFO] ${formattedMessage}`);
    try {
        sendLogToWindows('info', `${timestamp} ${formattedMessage}`);
    } catch (error) {
        originalInfo(`${timestamp} [ERROR] Error sending info log message:`, error);
    }
};

// 包装 log.error
const originalError = log.error;
log.error = (...args) => {
    const timestamp = `[${getTimestamp()}]`;
    const formattedMessage = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : arg)).join(' ');
    originalError(`${timestamp} [ERROR] ${formattedMessage}`);
    try {
        sendLogToWindows('error', `${timestamp} ${formattedMessage}`);
    } catch (error) {
        originalError(`${timestamp} [ERROR] Error sending error log message:`, error);
    }
};

// 新增 success 方法
log.success = (...args) => {
    const timestamp = `[${getTimestamp()}]`;
    const formattedMessage = args.map(arg => (typeof arg === 'object' ? JSON.stringify(arg) : arg)).join(' ');

    // 使用原始的 log.info 方法写入日志文件
    originalInfo(`${timestamp} [SUCCESS] ${formattedMessage}`);

    try {
        sendLogToWindows('success', `${timestamp} ${formattedMessage}`);
    } catch (error) {
        originalInfo(`${timestamp} [ERROR] Error sending success log message:`, error);
    }
};

module.exports = log;